package com.jdls.tanhua.server;

import cn.hutool.core.date.DateTime;
import com.jdls.tanhua.commons.utils.JwtUtils;
import com.jdls.tanhua.dubbo.UserApi;
import com.jdls.tanhua.exception.AllException;
import com.jdls.tanhua.pojo.User;
import com.jdls.tanhua.pojo.UserInfo;
import com.jdls.tanhua.template.HuanXinTemplate;
import com.jdls.tanhua.template.SmsTemplate;
import com.jdls.tanhua.vo.ErrorResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 嘉德罗斯
 * @date 2021/10/22
 */
@Service
public class UserServer {
    private final String TH = "tanhua";

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private UserApi userApi;

    public void sendMsg(String phone) {
        //String code ="";
        //Random r = new Random();
        //for (int i = 0; i < 6; i++) {
        //    int a = r.nextInt(10);
        //    code+=a;
        //}
        String code = "111111";
        //调用发送短信的方法
        //smsTemplate.sendSms(phone,code);
        redisTemplate.opsForValue().set(TH+phone,code,5L, TimeUnit.MINUTES);

    }

    public Map loginVerification(String phone, String code) {

        String s = redisTemplate.opsForValue().get(TH + phone);
        if (s==null){
            throw new AllException(ErrorResult.codeTimeout());
        }else if (!(code.equals(s))){
            throw new AllException(ErrorResult.codeErr());
        }

        //判断是否为新用户
        boolean ret = false;
        User user = userApi.findPhone(phone);
        if(user == null){
            user = new User();
            user.setCreated(DateTime.now());
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
            user.setUpdated(DateTime.now());
            user.setHxUser("hx"+user.getId());
            user.setHxPassword("111111");
            Long userId = userApi.save(user);
            user.setId(userId);
            //注册新用户到环信
            huanXinTemplate.createUser(user.getHxUser(),user.getHxPassword());
            ret = true;
        }
        
        Map map = new HashMap();
        map.put("id",user.getId());
        map.put("phone",phone);
        String token = JwtUtils.getToken(map);

        Map retMap = new HashMap();
        retMap.put("token",token);
        retMap.put("isNew",ret);
        return  retMap;
    }

}
